/*
 * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 */
package com.xinpan.exercise;


import java.util.Arrays;

public class ThreeSumClosest {
    public int threeSumClosest(int[] num, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int min = Integer.MAX_VALUE;
        int result = 0;
        int diff = 0;
        
        Arrays.sort(num);
        
        for(int i = 0; i < num.length - 2; i++)
        {
            for(int j = i+1, l = num.length - 1; j < l;)
            {
                int sum = num[i] + num[j] + num[l];
                
                if(sum > target)
                {
                    diff = sum - target;
                    if(diff < min)
                    {
                        result = sum;
                        min = diff;
                    }
                    l--;
                }
                else if(sum < target)
                {
                    diff = target - sum;
                    if(diff < min)
                    {
                        result = sum;
                        min = diff;
                    }
                    j++;
                }
                else
                    return target;
            }
        }
        return result;
    }
	    
	    public static void main(String[] args)
	    {
	    	ThreeSumClosest tsC = new ThreeSumClosest();
	    	
	    	int[] num = {0, 1, 2};
	    	int target = 0;
	    	int res = tsC.threeSumClosest(num, target);
	    	
	    	System.out.println(res);
	    }
}
